package com.common.app.web

import android.Manifest
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.R
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.WebInteractDataModel
import com.common.app.databinding.BaseActivityWebBinding
import com.common.app.helper.RouterHelper
import com.common.app.utls.EVENT_ACTIVITY_PAGE_VIEW
import com.common.app.utls.FIELD_ACTIVITY_ID
import com.common.app.utls.FIELD_CURRENT_PAGE_NAME
import com.common.app.utls.MyJavascriptInterface
import com.common.app.utls.TrackUtils
import com.common.base.app.extras.*
import com.common.base.listener.AlertDialogConfirmBtnListener
import com.common.base.listener.OnMyJavascriptInterfaceListener
import com.common.base.utils.AppUtils
import com.common.base.utils.IStringUtils
import com.common.base.utils.IStringUtils.getNewWebData
import com.common.base.utils.JsonUtils
import com.common.base.utils.RxPermissionHelper
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.VersionUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.PermissionRequest
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.*
import org.json.JSONObject
import java.io.InputStream

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/10/13
 * <p>
 * 描述：
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_BASE_WEB_ACTIVITY)
class BaseWebActivity : AppActivity<BaseActivityWebBinding, WebViewModel>(),
    OnMyJavascriptInterfaceListener {
    private val FILE_REQUEST_CODE = 345

    @Autowired(name = KeyBundle.PATH_URL)
    @JvmField
    var pathUrl: String? = null

    @Autowired(name = KeyBundle.WEB_DATA)
    @JvmField
    var webData: String? = null

    @Autowired(name = KeyBundle.WEB_TITLE)
    @JvmField
    var mWebTitle: String? = null

    @Autowired(name = KeyBundle.WEB_SHOW_TOOLBAR)
    @JvmField
    var showToolBar: Boolean = true

    @Autowired(name = KeyBundle.WEB_STATUS_BAR_TRANSLATE)
    @JvmField
    var isStatusBarTranslate: Boolean = false

    @Autowired(name = KeyBundle.WEB_SHOW_ARTICLE_TITLE)
    @JvmField
    var isShowArticleTitle: Boolean = false

    @Autowired(name = KeyBundle.WEB_ARTICLE_TIME)
    @JvmField
    var articleTime: String = ""

    @Autowired(name = KeyBundle.WEB_BIG_FONT)
    @JvmField
    var bigFont: Boolean = false

    @Autowired(name = KeyBundle.WEB_VIDEO_URL)
    @JvmField
    var videoUrl: String = ""

    @Autowired(name = KeyBundle.WEB_TYPE)
    @JvmField
    var mType: Int = 0//1公益2华为活体3黑鲨4客服5富文本内容6掌阅7商场商品详情8智能生活


    @Autowired(name = KeyBundle.GOODS_PARAMS_ID)
    @JvmField
    var activityId: String? = ""

    @Autowired(name = KeyBundle.GOODS_PARAMS_TYPE)
    @JvmField
    var type: String? = ""

    private var isTraceless = false
    private val whiteList: List<String>? = null

    private var uploadFiles: ValueCallback<Array<Uri>>? = null

    override fun isShowToolBar(): Boolean = showToolBar
    override fun isStatusBarTranslate() = isStatusBarTranslate
    override fun getViewContentBinding() = BaseActivityWebBinding.inflate(layoutInflater)

    override fun getViewModel(): Class<WebViewModel> = WebViewModel::class.java

    override fun getPageTitle(): String? {
        return mWebTitle.isNullOrEmpty().yes {
            AppUtils.getString(R.string.app_name_head)
        }.otherwise {
            if (mType == 5) {
                ""
            } else {
                mWebTitle
            }

        }
    }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarForegroundColor(this, true)
        initWebView()

        when (mType) {
            5 -> {
                getRightImageView().setImageDrawable(
                    ContextCompat.getDrawable(
                        this,
                        R.drawable.common_copy_small_icon
                    )
                )
                //显示右上角更多
                getRightImageView().isVisible = true
                setOnRightViewClickListener {
                    showDialogLoading()
                    // 全选 WebView 内容，并获取全选内容
                    mViewContentBinding.mWebView.postDelayed({
                        mViewContentBinding.mWebView.evaluateJavascript(
                            "javascript:document.execCommand('selectAll',false,null);"
                        ) {
                            mViewContentBinding.mWebView.evaluateJavascript(
                                "javascript:window.getSelection().toString()"
                            ) { value ->
                                dismissLoadingDialog()
                                IStringUtils.copy(
                                    this@BaseWebActivity,
                                    value.replace("\\n", "\n")
                                )
                                mViewContentBinding.mWebView.clearFocus()
                                mViewContentBinding.totalCl.isFocusable = true
                                mViewContentBinding.totalCl.isFocusableInTouchMode = true
                                showToast("文章内容已复制到粘贴板~")

                            }
                        }
                    }, 2000) // 延时 2 秒执行全选和获取选中内容操作

                }
            }
//            7->{
////                mViewBinding.toolbarInclude.toolbar =
//                getToolbarView().visibility = GONE
//            }
        }

//        AppConfigHelper.getSacrificeShow().yes {
//            //"公祭日"灰白模式
//            GrayManagerUtils.instance?.setLayerGrayType(mViewBinding.root)
//        }.otherwise {
//            //解除灰白模式
//            GrayManagerUtils.instance?.setLayerGrayType(0,mViewBinding.root)
//        }
    }


    override fun initEvents() {
        super.initEvents()
        mViewBinding.toolbarInclude.backViewTotal.setOnClickListener {
            when (mType) {
                2, 5, 8 -> finish()
                else -> {
                    if (mViewContentBinding.mWebView.canGoBack()) {
                        mViewContentBinding.mWebView.goBack()
                        return@setOnClickListener
                    }
                    finish()
                }
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (mType == 2) return
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                FILE_REQUEST_CODE -> {
                    if (null != uploadFiles) {
                        data?.data?.let {
                            uploadFiles?.onReceiveValue(arrayOf(it))
                        }
                        uploadFiles = null
                    }
                }

                else -> {
                }
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFiles) {
                uploadFiles?.onReceiveValue(null)
                uploadFiles = null
            }
        }
    }

    /**
     * init WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val webView = mViewContentBinding.mWebView
        webView.isLongClickable = true
        webView.overScrollMode = View.OVER_SCROLL_NEVER
        webView.isVerticalScrollBarEnabled = false
        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                this@BaseWebActivity.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                if (!TextUtils.isEmpty(view?.title) && TextUtils.isEmpty(mWebTitle)) {
                    if (mType == 5) {
                        setPageTitle("")
                    } else {
                        if (view?.title?.startsWith("https") != true && view?.title?.startsWith("http") != true) {
                            setPageTitle(view?.title)
                        }
                    }
                }
                getSmartRefreshLayout()?.finishRefresh()
                showContent()
                this@BaseWebActivity.onPageFinished(view, url)
                when (mType) {
                    3, 5 -> {//1公益2华为活体3学习园地4客服5富文本内容6掌阅
                        addImageClickListner(view)
                    }

                    else -> {
                    }
                }
            }

            override fun onReceivedError(
                view: WebView?,
                errorCode: Int,
                description: String?,
                failingUrl: String?
            ) {
                super.onReceivedError(view, errorCode, description, failingUrl)
                showError()
                getSmartRefreshLayout()?.finishRefresh()
            }

            override fun onReceivedSslError(
                p0: WebView?,
                handler: SslErrorHandler?,
                p2: com.tencent.smtt.export.external.interfaces.SslError?
            ) {
                handler?.proceed()
                getSmartRefreshLayout()?.finishRefresh()
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val url = request?.url?.toString() ?: ""

                val scheme = request?.url?.scheme ?: ""

                if (url.contains("tel") || scheme.contains("tel")) {

                    RxPermissionHelper.checkPermission(Manifest.permission.CALL_PHONE).yes {
                        val intent = Intent(Intent.ACTION_CALL, Uri.parse(url))
                        startActivity(intent)
                        return true
                    }.otherwise {

                        showToast("请开启通话权限！")
//                        RxPermissionHelper.request(this@BaseWebActivity, Manifest.permission.CALL_PHONE) {
//                        }
                        return true
                    }
                }

                try {
                    if (url.startsWith("weixin://") || url.startsWith("alipays://") || url.startsWith(
                            "niannian://"
                        )
                    ) {
                        //深链跳转
                        val action = Intent(Intent.ACTION_VIEW)
                        action.data = Uri.parse(url)
                        startActivity(action)
                        return true
                    }
                } catch (anf: ActivityNotFoundException) {
                    showToast("抱歉、找不到该页面！")
//                    Log.e("MarketUtils", "要跳转的应用市场不存在!")
                    return true
                } catch (e: Exception) {
                    Log.e("MarketUtils", "其他错误：" + e.message)
                    return true
                }

                return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    this@BaseWebActivity.shouldOverrideUrlLoading(view, request?.url?.toString())
                } else {
                    super.shouldOverrideUrlLoading(view, request)
                }
            }

            override fun doUpdateVisitedHistory(p0: WebView?, p1: String?, p2: Boolean) {
                if (isTraceless) {
                    p0?.clearHistory()
                }
                super.doUpdateVisitedHistory(p0, p1, p2)
            }

            override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse? {
                var pass = false
                if (!whiteList.isNullOrEmpty() && url != null) {
                    val var4: Iterator<*> = whiteList.iterator()
                    while (var4.hasNext()) {
                        val whiteKey = var4.next() as String
                        if (url.startsWith(whiteKey)) {
                            pass = true
                            break
                        }
                    }
                } else {
                    pass = true
                }

                return if (pass) super.shouldInterceptRequest(view, url) else WebResourceResponse(
                    null as String?,
                    null as String?,
                    null as InputStream?
                )
            }
        }

        // Android　4.0版本没有　WebChromeClient.FileChooserParams　这个类，所有要单独处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView?, newProgress: Int) {
                    if (isProgressBarLoading()) {
                        if (newProgress >= 100) {
                            showContent()
                        }
                    }
                }

                override fun onShowCustomView(
                    view: View?,
                    callback: IX5WebChromeClient.CustomViewCallback?
                ) {
                    webView.visibility = View.GONE
                }

                override fun onHideCustomView() {
                    webView.visibility = View.VISIBLE
                }

                //  5.0及以上调用
                override fun onShowFileChooser(
                    webView: WebView,
                    filePathCallback: ValueCallback<Array<Uri>>,
                    fileChooserParams: FileChooserParams
                ): Boolean {
                    if (mType == 2) return true

                    this@BaseWebActivity.uploadFiles = filePathCallback
                    openFileChooseProcess()
                    return true
                }

                override fun onPermissionRequest(request: PermissionRequest) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        request.grant(request.resources)
                    }
                }

                override fun onReceivedTitle(view: WebView?, title: String?) {
                    super.onReceivedTitle(view, title)
                    if (!TextUtils.isEmpty(title) && TextUtils.isEmpty(mWebTitle)) {
                        if (mType == 5) {
                            setPageTitle("")
                        } else {
                            if (title?.startsWith("https://") != true && title?.startsWith("http://") != true) {
                                setPageTitle(title)
                            }
                        }
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                            if (title?.contains("404") == true || title?.contains("500") == true || title?.contains(
                                    "Error"
                                ) == true
                            ) {
                                showError()
                            }
                        }
                    }
                }

                override fun onReceivedIcon(p0: WebView?, p1: Bitmap?) {
                    super.onReceivedIcon(p0, p1)
                }
            }
        }

        webView.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    finish()
                }
            }
            false
        }

        initWebViewSettings()

        addJavascriptInterface(webView)
        CookieManager.getInstance().setAcceptCookie(true)

        when (mType) {
            1 -> {//公益特殊处理
                StatusBarUtils.setStatusBarHeight(mViewBinding.statusView)
                mViewBinding.toolbarInclude.titleTv.setTextColor(getColor(R.color.white))
                mViewBinding.toolbarInclude.backView.setImageDrawable(getDrawable(R.drawable.base_back_white_icon))
                mViewBinding.toolbarInclude.toolbar.setBackgroundColor(getColor(R.color.c_a83535))
                mViewBinding.statusView.setBackgroundColor(getColor(R.color.c_a83535))
            }

            2 -> {
            }

            else -> {
            }
        }
    }

    private fun addJavascriptInterface(webView: WebView?) {
        when (mType) {
            2 -> {//华为活体
                //注入、反射
                webView?.addJavascriptInterface(MyJavascriptInterface(this, this), "cameraBridge")
            }
            else -> {
                val interact = WebInteract(this, this)
                webView?.addJavascriptInterface(interact, interact.name)
            }
        }
    }

    protected open fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        if (!isProgressBarLoading()) {
            showLoading()
        }
    }

    protected open fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        return false
    }

    /**
     * show file chooser
     *
     * @param filePathCallback
     */
    protected open fun onShowFileChooser(filePathCallback: ValueCallback<Uri>) {}

    protected open fun onPageFinished(view: WebView?, url: String?) {
        //解决白屏问题
        mViewContentBinding.mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        showContent()
    }

    /**
     * 是否使用进度条来呈现加载中占位图
     */
    protected open fun isProgressBarLoading(): Boolean = false

    override fun lazyInitData() {
        super.lazyInitData()
        pathUrl?.let {
//            //如果已经登录，并且是自家的H5页面 则加上TOKEN
//            var url = (UserHelper.isLogin() && it.startsWith(ApiConstant.getWebUrl())).yes {
//                //如果已经有带参数则用&符号 拼接token参数等
//                it + "${
//                    it.contains("?").judgeReturn("&", "?")
////                }token=${UserHelper.getToken()}&inviteCode=${UserHelper.getUser()?.inviteCode}"
//                }token=${UserHelper.getToken()}"
//            }.otherwise { it }
//            url += "${it.contains("?").judgeReturn("&", "?")}isApp=true"
//            LogUtils.e("===>WebView url:$url")
//            mViewContentBinding.mWebView.loadUrl(url)
            mViewContentBinding.mWebView.loadUrl(pathUrl)
        }

//        bigFont.yes {//字体放大
//            mViewContentBinding.mWebView.settings.textSize = WebSettings.TextSize.LARGEST
//        }

        webData?.let {
            when (mType) {
                8 -> {//智能生活
                    mViewContentBinding.articleTitleTotal.visibility = View.GONE
                }

                else -> {
                    isShowArticleTitle.yes {
                        mViewContentBinding.totalCl.setPadding(dp2px(15), 0, dp2px(15), 0)
                        mViewContentBinding.articleTitleTotal.visibility = View.VISIBLE
                        mViewContentBinding.articleTitleTv.text = mWebTitle
                        mViewContentBinding.timeTv.text = articleTime
                    }.otherwise {
                        mViewContentBinding.articleTitleTotal.visibility = View.GONE
                    }
                }
            }

//            mViewContentBinding.mWebView.loadData(it, "text/html", "utf-8")
            mViewContentBinding.mWebView.loadData(getNewWebData(it), "text/html", "utf-8")
//            mViewContentBinding.mWebView.loadData(getNewWebData(it), "text/html; charset=UTF-8", null)
        }

        videoUrl.isNullOrEmpty().no {
        }

        //专题/活动页  秒杀页浏览事件触发
        if (type in arrayOf("special", "seckill")) {
            onActivityPageExposure(activityId ?: "", type ?: "")
        }
    }

    private fun initWebViewSettings() {
        val webSetting: WebSettings = mViewContentBinding.mWebView.settings

//        mViewContentBinding.mWebView.removeJavascriptInterface("searchBoxJavaBridge_")

        mViewContentBinding.mWebView.setBackgroundColor(Color.TRANSPARENT)
        mViewContentBinding.mWebView.setBackgroundResource(R.color.transparent)


        // init webview settings
        webSetting.allowContentAccess = true
        webSetting.loadsImagesAutomatically = true
        webSetting.loadWithOverviewMode = true// 设置此属性，可任意比例缩放
        webSetting.databaseEnabled = true
        webSetting.domStorageEnabled = true
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        webSetting.setAppCacheEnabled(true)
        when (mType) {
            3 -> {//学习园地
            }

            else -> {
                webSetting.setSupportMultipleWindows(true)
                webSetting.javaScriptCanOpenWindowsAutomatically = true
            }
        }
        webSetting.allowFileAccess = true
        webSetting.savePassword = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSetting.cacheMode = WebSettings.LOAD_DEFAULT
        webSetting.setAllowFileAccessFromFileURLs(true)
        webSetting.pluginState = WebSettings.PluginState.ON

        //设置true,才能让Webivew支持<meta>标签的viewport属性
//        webSetting.useWideViewPort = true

////        //设置可以支持缩放
////        webSetting.setSupportZoom(true)
////        //设置出现缩放工具
////        webSetting.builtInZoomControls = true
////        //设定缩放控件隐藏
////        webSetting.displayZoomControls = true

        webSetting.defaultTextEncodingName = "utf-8"//防止乱码

        // 设置可以访问文件
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS

        // 启用javascript脚本
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)

        // 解决百度地位空白问题
        webSetting.loadsImagesAutomatically = true // 设置WebView是否加载图片资源，默认true，自动加载图片
        webSetting.blockNetworkImage = false //设置网页在加载的时候暂时不加载图片
        webSetting.blockNetworkLoads = false //设置是否从网络下载数据

        // 解决定位偏差问题
        webSetting.setGeolocationDatabasePath(
            getDir("geolocation", 0)
                .path
        )

        // 设置它可以解决部分手机视频不能播放的问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
        }

        val version: String = getSource()
        val ua = webSetting.userAgentString
        webSetting.userAgentString = ua + "ds/" + version
    }

    fun getSource(): String {
        return "1;${VersionUtils.getVerName(AppUtils.getContext())};${AppUtils.getChannel()}"
    }

    override fun onBackPressedSupport() {
//        if(getPlaceholderView()?.isLoading() == true){
//            showContent()
//            return
//        }
        when (mType) {
            2, 5, 8 -> super.onBackPressedSupport()
            else -> {
                if (mViewContentBinding.mWebView.canGoBack()) {
                    mViewContentBinding.mWebView.goBack()
                    return
                }
                super.onBackPressedSupport()
            }
        }

    }

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mViewContentBinding.mWebView != null) {
            mViewContentBinding.mWebView.stopLoading()
            mViewContentBinding.mWebView.removeAllViewsInLayout()
            mViewContentBinding.mWebView.removeAllViews()
            mViewContentBinding.mWebView.webViewClient = null
            mViewContentBinding.mWebView.destroy()
        }
        // 清除 WebView 中保存的所有 cookie
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookies(null)
        cookieManager.flush()

    }

    override fun onBackClick() {
        when (mType) {
            2, 5, 8 -> super.onBackPressedSupport()
            3 -> {
                if (mViewContentBinding.mWebView.canGoBack()) {
                    mViewContentBinding.mWebView.goBack()
                    return
                }
                super.onBackClick()
            }

            else -> super.onBackClick()
        }
    }

    override fun onStartFunction(data: String?) {
        val interactionModelTemp: WebInteractDataModel = data?.let {
            JsonUtils.fromJson(
                it,
                WebInteractDataModel::class.java
            )
        } ?: return


        // 链接类型(0:内部跳转 1.app跳转 2:h5跳转3打开新web页面)
        when (interactionModelTemp.urlType) {
            0 -> {

            }

            1 -> {
                try {
                    //深链跳转
                    val action = Intent(Intent.ACTION_VIEW)
                    action.data = Uri.parse(interactionModelTemp.androidAppUrl)
                    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(action)
                } catch (anf: ActivityNotFoundException) {
                    showAlertDialogTwoBtn(
                        getString(R.string.cancel_btn_zh),
                        getString(R.string.ok_btn_zh2),
                        "提示",
                        "确认去下载${interactionModelTemp.title}应用?",
                        message2="",
                        true,
                        object : AlertDialogConfirmBtnListener {
                            override fun onCancelBtnClick() {
                            }

                            override fun onConfirmBtnClick() {
                                AppUtils.startBrowser(interactionModelTemp.androidDownloadUrl)
                            }
                        }
                    )
                }
            }

            2 -> {
//                doOnUiThread {
//                }
            }

            3 -> {
                interactionModelTemp.urlLink?.let {
                    doOnUiThread {
                        RouterHelper.navigationPostcard(RouterHub.ROUTER_BASE_WEB_ACTIVITY)
                            .withString(KeyBundle.PATH_URL, it)
                            .navigation()
                    }
                }
            }

            else -> {

            }
        }
    }

    override fun onHwStartFunction(data: String?) {
        finish()
        LiveEventBus.get(KeyEvents.MSG_TYPE_HW_FACE_DATA)
            .post(data)
    }

    // 注入js函数监听
    private fun addImageClickListner(view: WebView?) {
        //遍历页面中所有img的节点，因为节点里面的图片的url即objs[i].src，保存所有图片的src.
        //为每个图片设置点击事件，objs[i].onclick
        view?.loadUrl(
            "javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); "
                    + "var imgurls=''; "
                    + "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "imgurls+=objs[i].src+',';"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window.WebInteract.openImage(imgurls ,this.src);  " +
                    "    }  " +
                    "}" +
                    "})()"
        )

    }

    private fun openFileChooseProcess() {
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "*/*"
        startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_REQUEST_CODE)
    }

    private fun sedDataToH5(mData: String?) {
        val javascript = "javascript:javatojscallback('$mData')" // 组装调用函数的 JavaScript 语句
        mViewContentBinding.mWebView.loadUrl(javascript) // 调用 H5 中的 showMessage 函数，并将 message 作为参数传递

    }

    //活动页浏览事件
    fun onActivityPageExposure(id: String, name: String) {
        var activityName = when (name) {
            //秒杀
            "seckill" -> getString(com.common.app.R.string.bsstore_activity_secondkill)

            //专题活动页
            "special" -> getString(com.common.app.R.string.bsstore_activity)

            else -> ""
        }
        val properties = JSONObject()
        try {
            properties.putOpt(FIELD_ACTIVITY_ID, id)
            properties.putOpt(FIELD_CURRENT_PAGE_NAME, activityName)
        } catch (e: Exception) {
            properties
        }
        TrackUtils.track(EVENT_ACTIVITY_PAGE_VIEW, properties)
    }
}